package com.itheima.aop;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class LoginAop {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;
    @Around("@annotation(com.itheima.anno.login)")
    public Object loginAspect(ProceedingJoinPoint pjp) throws Throwable {

        Object[] args1 = pjp.getArgs();
        Emp arg = (Emp) args1[0];

        //登陆时间
        LocalDateTime loginTime = LocalDateTime.now();
        //耗时
        long start = System.currentTimeMillis();
        Result proceed = (Result) pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end-start;

        EmpLoginLog empLoginLog = new EmpLoginLog();

        String password = arg.getPassword();
        String username = arg.getUsername();



        short isSuccess = proceed.getCode().shortValue();
        if(isSuccess==1){
            LoginInfo data1 = (LoginInfo)proceed.getData();
            empLoginLog.setJwt(data1.getToken());
        }else {
             empLoginLog.setJwt("null");
        }

        empLoginLog.setUsername(username);
        empLoginLog.setPassword(password);
        empLoginLog.setLoginTime(loginTime);
        empLoginLog.setIsSuccess(isSuccess);
        empLoginLog.setCostTime(costTime);


        empLoginLogMapper.insert(empLoginLog);


        return proceed;
    }



}
